﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraTab;
using DevTeam;


using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Siparisler
{
    public partial class FabricNeed : XForm
    {
        //RepositoryItemSearchLookUpEdit riArts;
        int Marka = 0;
        public FabricNeed(int _Marka)
        {
            InitializeComponent();

            Marka = _Marka;
            TAM.ModelTableAdapter = new Datasets.MyDataTableAdapters.ModelTableAdapter();
            //string[] arts = _arts.Split(';');

            //riArts = RI(Rp.V_Kumas).Clone() as RepositoryItemSearchLookUpEdit;
            //riArts.DataSource = new DataView(AppSession.Lookups.V_Kumas, "ProductId in (" + _arts.Replace(";", ",") + ")", "Name", DataViewRowState.OriginalRows);
        }

        private void Expressions(bool set)
        {
            if (set)
            {
                ds.FNIhtiyac.Columns["LineTotal"].Expression = "SipAdet*(AnaBedenQty+GarniQty)";
                ds.FNIhtiyac.Columns["FazlaAlimFarki"].Expression = "SipAdet*(AnaBedenQty*" + A_FAO.ToString().Replace(",", ".") + " + GarniQty*" + G_FAO.ToString().Replace(",", ".") + ")";
                ds.FNIhtiyac.Columns["DarEnFarki"].Expression = "(LineTotal+FazlaAlimFarki)*(150/ENG-1)";
                ds.FNIhtiyac.Columns["FinalTotal"].Expression = "(LineTotal+FazlaAlimFarki+DarEnFarki)";
            }
            else
                ds.FNIhtiyac.Columns["LineTotal"].Expression = ds.FNIhtiyac.Columns["FazlaAlimFarki"].Expression = ds.FNIhtiyac.Columns["DarEnFarki"].Expression = ds.FNIhtiyac.Columns["FinalTotal"].Expression = string.Empty;
        }

        //public int FNId = 0;
        decimal A_FAO = 0.05m, G_FAO = 0.10m;
        public MyData.xFNAktarDataTable NeedTable = null;
        BindingSource bs0, bs1, bs2, bsKumas, bsCoverage;
        private void FabricNeed_Load(object sender, EventArgs e)
        {

            Expressions(true);


            DataTable dtKumas = new DataTable("Artikel");
            dtKumas.Columns.Add("ProductId", typeof(int));
            dtKumas.PrimaryKey = new DataColumn[] { dtKumas.Columns[0] };
            ds.Tables.Add(dtKumas);

            bsKumas = new BindingSource(ds, "Artikel");
            InitGridView(gvKumas, bsKumas);
            gvKumas.OptionsBehavior.Editable = false;
            sleKumas.Properties.Assign(RI(Rp.V_Kumas));
            bsKumas.CurrentChanged += new EventHandler(bsKumas_CurrentChanged);
            sleKumas.EditValueChanged += new EventHandler(sleKumas_EditValueChanged);

            bs0 = new BindingSource(ds, "Model");
            AddBsToList(bs0);

            gleCustomer.Properties.Assign(RI(Rp.V_Customer));
            bs1 = new BindingSource(ds, "xFNLines");
            bs2 = new BindingSource(ds, "FNIhtiyac");
            bsCoverage = new BindingSource(ds, "xFNCoverage");

            InitGridView(gvModel, bs0);
            InitGridView(gvKullanim, bs1);
            InitGridView(gvIhtiyac, bs2);
            InitGridView(gvCoverage, bsCoverage);

            gvModel.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            //gvKullanim.Columns["AnaBedenArt"].ColumnEdit = gvKullanim.Columns["Garni1Art"].ColumnEdit = gvKullanim.Columns["Garni2Art"].ColumnEdit = gvKullanim.Columns["Garni3Art"].ColumnEdit = gvKullanim.Columns["Garni4Art"].ColumnEdit = gvKullanim.Columns["Garni5Art"].ColumnEdit = riArts; // RI(Rp.V_Kumas);

            btnBasla.Click += new EventHandler(btnYeni_Click);
            gleCustomer.EditValueChanged += new EventHandler(gleCustomer_EditValueChanged);

            AddGroupSummary(gvIhtiyac, "SipAdet", "LineTotal", "FazlaAlimFarki", "DarEnFarki", "FinalTotal", "AdjustedTotal");
            gvIhtiyac.FormatAsNumber(2, "LineTotal", "FazlaAlimFarki", "DarEnFarki", "FinalTotal", "AdjustedTotal");
            gvIhtiyac.MakeColumnInvisible("FNId", "ENG", "EnGrubuId", "Scan", "ProductId");
            gvKullanim.MakeColumnInvisible("FNId", "xFNLinesId", "Scan", "ProductId");
            gvCoverage.Columns["Mx"].Visible = false;
            gvModel.Columns["CustomerId"].Visible = false;
            gvModel.OptionsBehavior.Editable = gvCoverage.OptionsBehavior.Editable = false;

            cmbA.Properties.DisplayFormat.FormatType = FormatType.Numeric;
            cmbA.Properties.DisplayFormat.FormatString = "p0";

            cmbG.Properties.DisplayFormat.FormatType = FormatType.Numeric;
            cmbG.Properties.DisplayFormat.FormatString = "p0";

            cmbA.Properties.Items.AddRange(new object[] { 0.00, 0.01, 0.02, 0.03, 0.05, 0.08, 0.10, 0.15 });
            cmbG.Properties.Items.AddRange(new object[] { 0.00, 0.02, 0.03, 0.05, 0.08, 0.10, 0.15, 0.20 });

            cmbA.EditValue = A_FAO;
            cmbG.EditValue = G_FAO;
            cmbA.EditValueChanged += new EventHandler(cmb_EditValueChanged);
            cmbG.EditValueChanged += new EventHandler(cmb_EditValueChanged);
            pnlOran.Visible = false;

            gvIhtiyac.CustomDrawGroupRow += new RowObjectCustomDrawEventHandler(gvArtikel_CustomDrawGroupRow);
            gvIhtiyac.CellValueChanged += new CellValueChangedEventHandler(gvArtikel_CellValueChanged);
            btnBasla.Enabled = false;

            gvKullanim.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(gvSiparis_RowCellStyle);
            //gm = GridManager.GetManager(gvKullanim);
            //gm.GridMenu.AddMenu("Satırı Çoğalt", SatiriCiftle_Click);
            gvKullanim.OptionsBehavior.ImmediateUpdateRowPosition = true;

            gvKullanim.ClearSorting();
            gvKullanim.Columns["ModelId"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            EnableTabPage(tpModeller);

            //chkDisabled.Appearance --> disableEt
            gvKullanim.CustomRowCellEdit += new global::DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventHandler(gvKullanim_CustomRowCellEdit);

            gvKullanim.MouseDown += new MouseEventHandler(gvKullanim_MouseDown);
            gvIhtiyac.AddSummary("AnaBedenQty", "GarniQty", "LineTotal", "FazlaAlimFarki", "DarEnFarki", "FinalTotal", "AdjustedTotal");
            btnTalepOlustur.Click += new EventHandler(btnTalepOlustur_Click);

            if (Marka > 0)
                gleCustomer.EditValue = AppSession.Lookups.Brand.FindByBrandId(Marka).CustomerId;

            gvCoverage.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(gvCoverage_RowCellStyle);

            btnNext.Visible = false;
            btnNext.Click += new EventHandler(btnNext_Click);

            tpCoverage.PageVisible = false;
            btnTalepOlustur.Enabled = false;
        }

        void btnNext_Click(object sender, EventArgs e)
        {
            ds.xFNCoverage.Clear();
            ds.FNIhtiyac.Clear();
            DataTable dt = ds.xFNLines.Select("SipAdet>0").CopyToDataTable<DataRow>();
            GetDetails("xFNCoverage;FNIhtiyac", "UpdFN", 2, string.Empty, dt.Serialize(), CustomerId, decimalParse(cmbA.EditValue), decimalParse(cmbG.EditValue), WhoAmI);
            //FNId = ds.FN[0].FNId;
            gvIhtiyac.Columns["ProductId"].Group();
            gvIhtiyac.ExpandAllGroups();
            gvIhtiyac.BestFitColumns();
            gvCoverage.BestFitColumns();

            bool covers = true;
            foreach (MyData.xFNCoverageRow r in ds.xFNCoverage)
            {
                if (!r.IsABNull() && r.AB < r.Mx ||
                    !r.IsG1Null() && r.G1 < r.Mx ||
                    !r.IsG2Null() && r.G2 < r.Mx ||
                    !r.IsG3Null() && r.G3 < r.Mx ||
                    !r.IsG4Null() && r.G4 < r.Mx ||
                    !r.IsG5Null() && r.G5 < r.Mx)
                    covers = false;
            }

            tpCoverage.PageVisible = !covers;
            tabAna.SelectedTabPage = !covers ? tpCoverage : tpIhtiyac;
            btnTalepOlustur.Enabled = covers;
        }

        void gvCoverage_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if ((e.Column.FieldName == "AB" || e.Column.FieldName.StartsWith("G")) &&
                e.CellValue != DBNull.Value &&
                intParse(e.CellValue) < intParse(gvCoverage.GetRowCellValue(e.RowHandle, "Mx")))
                e.Appearance.BackColor = Color.YellowGreen;
        }

        void sleKumas_EditValueChanged(object sender, EventArgs e)
        {
            if (sleKumas.EditValue == null)
                return;

            if (!ds.Tables["Artikel"].Rows.Contains(intParse(sleKumas.EditValue)))
            {
                ds.Tables["Artikel"].Rows.Add(intParse(sleKumas.EditValue));
                gvKumas.EndEditing();

                foreach (MyData.ModelRow m in ds.Model.Select("CustomerId = " + gleCustomer.EditValue.ToString()))
                {
                    MyData.xFNLinesRow f = ds.xFNLines.NewxFNLinesRow();
                    if (!m.IsAnaBedenQtyNull())
                        f.AnaBedenQty = m.AnaBedenQty;
                    if (!m.IsGarni1QtyNull())
                        f.Garni1Qty = m.Garni1Qty;
                    if (!m.IsGarni2QtyNull())
                        f.Garni2Qty = m.Garni2Qty;
                    if (!m.IsGarni3QtyNull())
                        f.Garni3Qty = m.Garni3Qty;
                    if (!m.IsGarni4QtyNull())
                        f.Garni4Qty = m.Garni4Qty;
                    if (!m.IsGarni5QtyNull())
                        f.Garni5Qty = m.Garni5Qty;
                    if (!m.IsNameNull())
                        f.Model = m.Name;
                    if (!m.IsNotesNull())
                        f.Notes = m.Notes;

                    f.ModelId = m.ModelId;
                    f.ProductId = intParse(sleKumas.EditValue);

                    ds.xFNLines.AddxFNLinesRow(f);
                }
            }

            //OPS.. burası çalışıyor mu kontrol et.
            gvKumas.FocusedRowHandle = gvKumas.LocateByValue(0, gvKumas.Columns["ProductId"], intParse(sleKumas.EditValue));
            //gvKumas.MakeRowVisible(gvKumas.FocusedRowHandle, true);
            gvKumas.TopRowIndex = gvKumas.FocusedRowHandle;
            gvKullanim.BestFitColumns();
        }

        void btnTalepOlustur_Click(object sender, EventArgs e)
        {
            EnableTabPage(tpIhtiyac);
            Expressions(false);
            DataTable dt = ds.xFNLines.Select("SipAdet>0").CopyToDataTable<DataRow>();
            GetDetails("xFNAktar", "UpdFN", 3, ds.FNIhtiyac.Serialize(), dt.Serialize(), CustomerId, A_FAO, G_FAO, WhoAmI);
            Expressions(true);
            NeedTable = ds.xFNAktar;
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }
        RepositoryItemCheckEdit chkEnabled = new RepositoryItemCheckEdit();

        private void gvKullanim_MouseDown(object sender, MouseEventArgs e)
        {
            GridHitInfo hitInfo = gvKullanim.CalcHitInfo(e.Location);
            if (hitInfo.InRowCell)
            {
                if (hitInfo.Column.RealColumnEdit is RepositoryItemCheckEdit)
                {
                    gvKullanim.FocusedColumn = hitInfo.Column;
                    gvKullanim.FocusedRowHandle = hitInfo.RowHandle;
                    gvKullanim.ShowEditor();
                    CheckEdit edit = gvKullanim.ActiveEditor as CheckEdit;
                    if (edit == null) return;
                    edit.Toggle();
                    DXMouseEventArgs.GetMouseArgs(e).Handled = true;
                }
            }
        }

        void gvKullanim_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            switch (e.Column.FieldName)
            {
                case "AB": e.RepositoryItem = (gvKullanim.GetRowCellValue(e.RowHandle, "AnaBedenQty") != DBNull.Value ? chkEnabled : new RepositoryItem()); break;
                case "G1": e.RepositoryItem = (gvKullanim.GetRowCellValue(e.RowHandle, "Garni1Qty") != DBNull.Value ? chkEnabled : new RepositoryItem()); break;
                case "G2": e.RepositoryItem = (gvKullanim.GetRowCellValue(e.RowHandle, "Garni2Qty") != DBNull.Value ? chkEnabled : new RepositoryItem()); break;
                case "G3": e.RepositoryItem = (gvKullanim.GetRowCellValue(e.RowHandle, "Garni3Qty") != DBNull.Value ? chkEnabled : new RepositoryItem()); break;
                case "G4": e.RepositoryItem = (gvKullanim.GetRowCellValue(e.RowHandle, "Garni4Qty") != DBNull.Value ? chkEnabled : new RepositoryItem()); break;
                case "G5": e.RepositoryItem = (gvKullanim.GetRowCellValue(e.RowHandle, "Garni5Qty") != DBNull.Value ? chkEnabled : new RepositoryItem()); break;
            }
        }


        int Artikel;
        void bsKumas_CurrentChanged(object sender, EventArgs e)
        {
            Artikel = intParse(((DataRowView)bsKumas.Current).Row["ProductId"]);
            bs1.Filter = /*bs2.Filter =*/ "ProductId = " + Artikel.ToString();
        }

        void SatiriCiftle_Click(object sender, EventArgs e)
        {
            DataRow dr = ds.xFNLines.NewRow();
            //int NeedLinesId = (int)dr["NeedLinesId"];
            if (gvKullanim.FocusedRowHandle > -1)
            {
                dr.ItemArray = gvKullanim.GetDataRow(gvKullanim.FocusedRowHandle).ItemArray;

                dr["SipAdet"] = DBNull.Value;
                //dr["NeedLinesId"] = NeedLinesId;
                //dr["AnaBedenArt"] = null;
                //dr["Garni1Art"] = null;
                ds.xFNLines.Rows.Add(dr);
            }
        }


        void gvSiparis_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName.EndsWith("Qty"))
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
            else if (e.Column.FieldName == "SipAdet")
            {
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                e.Appearance.BackColor = System.Drawing.Color.DarkGray; // FromArgb(238, 243, 213);
            }
        }

        void gvArtikel_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            gvIhtiyac.UpdateCurrentRow();
            gvIhtiyac.UpdateGroupSummary();
            //gvArtikel.UpdateTotalSummary();
        }

        void cmb_EditValueChanged(object sender, EventArgs e)
        {
            A_FAO = decimalParse(cmbA.EditValue);
            G_FAO = decimalParse(cmbG.EditValue); //decimal.Parse(cmbG.EditValue.ToString(), CultureInfo.InvariantCulture);
            ds.FNIhtiyac.Columns["FazlaAlimFarki"].Expression = "SipAdet*(AnaBedenQty*" + A_FAO.ToString().Replace(",", ".") + " + GarniQty*" + G_FAO.ToString().Replace(",", ".") + ")";
            gvIhtiyac.RefreshData();
        }

        int CustomerId = 0;
        void gleCustomer_EditValueChanged(object sender, EventArgs e)
        {
            btnBasla.Enabled = (gleCustomer.EditValue != null);
            ds.Model.Clear();
            CustomerId = intParse(gleCustomer.EditValue);
            GetDetails("Model", "UpdFN", 0, string.Empty, string.Empty, CustomerId, 0, 0, WhoAmI);
            gvModel.Columns["Name"].Caption = "Model";
            gvModel.BestFitColumns();
        }

        void EnableTabPage(XtraTabPage tp)
        {
            try
            {
                switch (tp.Name)
                {
                    case "tpKullanim":
                    case "tpIhtiyac": tpModeller.PageVisible = false; tpKullanim.PageVisible = /*tpCoverage.PageVisible =*/ tpIhtiyac.PageVisible = btnNext.Visible = true; break;
                    case "tpModeller": tpModeller.PageVisible = true; tpKullanim.PageVisible = tpCoverage.PageVisible = tpIhtiyac.PageVisible = btnNext.Visible = false; break;
                }

            }
            finally
            {
                tabAna.SelectedTabPage = tp;
            }

            //foreach (XtraTabPage p in tabAna.TabPages)
            //    p.PageEnabled = (p == tp);
            //tabAna.SelectedTabPage = tp;

            btnBasla.Enabled = lblCustomer.Enabled = gleCustomer.Enabled = tp == tpModeller;
            lblKumaslar.Enabled = sleKumas.Enabled = tp == tpKullanim;
            pnlOran.Visible = tp == tpIhtiyac;
        }

        void btnYeni_Click(object sender, EventArgs e)
        {
            EnableTabPage(tpKullanim);
            /*
            switch (btnBasla.Text)
            {
                case "&Başla":
                    //ds.xFNLines.Clear();
                    //GetDetails("xFNLines", "UpdFN", 1, string.Empty, intParse(gleCustomer.EditValue), 0, 0, WhoAmI);
                    //gvKullanim.BestFitColumns();
                    //btnBasla.Text = "Hesa&pla";
                    break;
                /*
                case "Hesa&pla":
                    EnableTabPage(tpIhtiyac);
                    //GetDetails("FN;FNIhtiyac", "UpdFN", 2, XML.Serialize(ds.xFNLines), CustomerId, 0, 0, WhoAmI);
                    //FNId = ds.FN[0].FNId;
                    //gvIhtiyac.Columns["ProductId"].Group();
                    //gvIhtiyac.ExpandAllGroups();
                    //gvIhtiyac.BestFitColumns();
                    //pnlOran.Visible = true;
                    //btnBaslaBitir.Text = "Talep &oluştur";
                    break;

                case "Talep &oluştur":
                    Expressions(false);
                    GetDetails("xFNAktar", "UpdFN", 3, XML.SerializeAll(ds.FNIhtiyac), CustomerId, A_FAO, G_FAO, WhoAmI);
                    Expressions(true);
                    NeedTable = ds.xFNAktar;
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    break;

            }
                 */
        }

        /*
        void Model_TableNewRow(object sender, System.Data.DataTableNewRowEventArgs e)
        {
            e.Row["CustomerId"] = intParse(gleCustomer.EditValue);
            e.Row["UserId"] = WhoAmI;
        }

        void btnModelKaydet_Click(object sender, EventArgs e)
        {
            Save();
        }
        */
        private void gvArtikel_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
        {
            object val = gvIhtiyac.GetGroupRowValue(e.RowHandle);
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo info = e.Info as GridGroupRowInfo;
            if (info.Column.FieldName == "ProductId")
            {
                int ProductId = intParse(gvIhtiyac.GetGroupRowValue(e.RowHandle));
                string ENG = AppSession.Lookups.EnGrubu.Select("ENG=" + ds.FNIhtiyac.Select("ProductId=" + ProductId.ToString())[0]["ENG"].ToString())[0]["Name"].ToString();
                info.GroupText = AppSession.Lookups.V_Kumas.FindByProductId(ProductId).Name +
                    "  (EN " + ENG + ")" + (string.Compare(ENG, "131") < 0 ? "  *Dikkat: DAR EN!" : string.Empty);
            }
            // Gets the summary text.
            //string sumText = gridView1.GetGroupSummaryText(info.RowHandle);
            // Replace the group row's default text.
            //info.GroupText = "Artikel: " + gvArtikel.GetRowCellDisplayText(info.RowHandle, "ProductId") + " ( EN " + gvArtikel.GetRowCellDisplayText(info.RowHandle, "ENG") + " )" + (string.Compare(gvArtikel.GetRowCellDisplayText(info.RowHandle, "ENG"), "131") < 0 ? "   DİKKAT: DAR EN!" : string.Empty); // +sumText;
        }


        // Gets the text representing the interval that contains the specified value.
        //string IntervalByValue(object val)
        //{
        //    double d = Math.Floor(Convert.ToDouble(val) / 100);
        //    string ret = string.Format("{0:c} - {1:c} ", d * 100, (d + 1) * 100);
        //    if (d > 14) ret = string.Format(">= {0:c} ", d * 100);
        //    return ret;
        //}


        //Skin currentSkin = CommonSkins.GetSkin(defaultLookAndFeel1.LookAndFeel);
        //Color c = currentSkin.TranslateColor(SystemColors.Control);


        //gvArtikel.BeginDataUpdate();
        // // this builds the sort array into the variable sortInfo
        // GridColumnSortInfo[] sortInfo = 
        //{
        // new GridColumnSortInfo(gvArtikel.Columns["ProductId"],ColumnSortOrder.Ascending),
        // new GridColumnSortInfo(gvArtikel.Columns["ENG"],ColumnSortOrder.Ascending)
        // };
        // // this adds the grouping - the integer defines how many columns in the sortInfo variable will be grouped
        // gvArtikel.SortInfo.ClearAndAddRange(sortInfo, 1);

        // gvArtikel.EndDataUpdate();
    }
}